﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors.Controls;
using System.Collections;
using TERP.Constants;
using TERP.HTCServiceClient.Views;
using TERP.HTCServiceClient.Entities.Auth;
using TERP.HTCServiceClient.Common;
using TERP.HTCServiceClient.DbServices;

namespace TERP.HTCServiceClient.Views.Auth
{
	public partial class FrmMngUser : FrmMdiBase
	{
		#region Declarations
		private const string CAPTION_INDEX = "STT";
		private const string CAPTION_GRP_CODE = "Mã nhóm";
		private const string CAPTION_GRP_NAME = "Tên nhóm";
		private const string CAPTION_EDIT_STATUS = "Trạng thái";
		//
		private const string CAPTION_USR_CODE = "Mã người dùng";
		private const string CAPTION_USR_NAME = "Tên người dùng";
		private const string CAPTION_PASSWORD = "Mật khẩu";
		private const string CAPTION_DEALER_NAME = "Đại lý";
		private const string CAPTION_DEALER_CODE = "Mã";
		private const string CAPTION_FLAG_SYS_ADMIN = "Sys Admin";
		//
		private const string CAPTION_IDX = "STT";
		private const string CAPTION_OBJ_CODE = "Mã chức năng";
		private const string CAPTION_OBJ_TYPE = "Loại chức năng";
		private const string CAPTION_PARTNER_CODE = "Loại ứng dụng";
		private const string CAPTION_OBJ_NAME = "Tên chức năng";
		private const string CAPTION_FLAG_ACTIVE = "Kích hoạt";

		//
		private const string FIELD_EDIT_STATUS = "Col_Edit_Status";
		//
		private const string MSG_WARNING_EMPTY_VALUE = "Không được trống";
		private const string MSG_WARNING_TOO_SHORT_PWD = "Mật khẩu phải dài hơn 5 kí tự";
		private const string MSG_WARNING_DUPLICATE_GRP_CODE = "Mã nhóm đã tồn tại";

		private UserCollection _userCollection;
		private Hashtable _htblGrpContain;
		private Hashtable _htblFunction;
		#endregion


		public FrmMngUser()
		{
			InitializeComponent();
		}

		private void FrmMngUser_Load(object sender, EventArgs e)
		{
			InitGrid();
			InitGridItemEditor();
			InitControl();
			SetLanguage();
			this.LoadUser();
		}

		private void InitControl()
		{
			_htblGrpContain = new Hashtable();
			_htblFunction = new Hashtable();
			//
			this.reposCheckEdit.ValueChecked = Flag.Active;
			this.reposCheckEdit.ValueUnchecked = Flag.Inactive;
			//
			this.reposCheckEditObjActive.ValueChecked = Flag.Active;
			this.reposCheckEditObjActive.ValueUnchecked = Flag.Inactive;
		}

		/// <summary>
		/// 
		/// </summary>
		private void SetLanguage()
		{
			this.grpUser.Text = "Người dùng";
			this.grpProperties.Text = "Thuộc tính";
			this.btnDelete.Text = "Xóa";
			this.btnApply.Text = "Lưu";
			this.btnAdd.Text = "Thêm";
			this.btnClose.Text = "Đóng";
			this.btnReload.Text = "Tải lại";
			this.btnEdit.Text = "Sửa";
			//
			this.tabPageGrpContain.Text = "Nhóm";
			this.tabPageFunctionObj.Text = "Chức năng";
		}

		/// <summary>
		/// 
		/// </summary>
		private void InitGrid()
		{
			SetGridViewStyle(gviewUser);
			SetGridViewStyle(gviewGrpContain);
            SetGridViewStyle(gviewObjBelong);
			//grid user
			gridColUserIdx.Caption = CAPTION_INDEX;
			gridColUserCode.Caption = CAPTION_USR_CODE;
			gridColUserName.Caption = CAPTION_USR_NAME;
			gridColPassword.Caption = CAPTION_PASSWORD;
			gridColFlagActive.Caption = CAPTION_FLAG_ACTIVE;
			gridColEditStatus.Caption = CAPTION_EDIT_STATUS;
			//
			gridColUserIdx.FieldName = TblCommon.Index;
			gridColUserCode.FieldName = TblUser.User_Code;
			gridColUserName.FieldName = TblUser.User_Name;
			gridColPassword.FieldName = TblUser.User_Password;
			gridColFlagActive.FieldName = TblUser.Flag_Active;
			gridColEditStatus.FieldName = FIELD_EDIT_STATUS;
			//grid group
			gridColGrpIdx.Caption = CAPTION_INDEX;
			gridColGroupCode.Caption = CAPTION_GRP_CODE;
			gridColGroupName.Caption = CAPTION_GRP_NAME;
			//
			gridColGrpIdx.FieldName = TblCommon.Index;
			gridColGroupCode.FieldName = TblGroup.Group_Code;
			gridColGroupName.FieldName = TblGroup.Group_Name;
			//grid function
			this.gridColObjIdx.FieldName = TblCommon.Index;
			this.gridColObjCode.FieldName = TblFunctionObject.Object_Code;
			this.gridColObjType.FieldName = TblFunctionObject.Object_Type;
			this.gridColObjPartnerCode.FieldName = TblFunctionObject.Partner_Code;
			this.gridColObjName.FieldName = TblFunctionObject.Object_Name;
			this.gridColObjFlagActive.FieldName = TblFunctionObject.Flag_Active;
			//
			this.gridColObjIdx.Caption = CAPTION_IDX;
			this.gridColObjCode.Caption = CAPTION_OBJ_CODE;
			this.gridColObjType.Caption = CAPTION_OBJ_TYPE;
			this.gridColObjPartnerCode.Caption = CAPTION_PARTNER_CODE;
			this.gridColObjName.Caption = CAPTION_OBJ_NAME;
			this.gridColObjFlagActive.Caption = CAPTION_FLAG_ACTIVE;	
		}

		/// <summary>
		/// 
		/// </summary>
		private void InitGridItemEditor()
		{
			reposImgCmbBox.SmallImages = EmbeddedRes.Instance.ImageListEditStatus;
			reposImgCmbBox.Items.Clear();
			reposImgCmbBox.Items.AddRange(new ImageComboBoxItem[] { 
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_NONE, EditStatus.IMG_IDX_STT_NONE), 
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_EDIT, EditStatus.IMG_IDX_STT_EDIT),
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_DELETE, EditStatus.IMG_IDX_STT_DELETE),
				new ImageComboBoxItem("",EditStatus.ITEM_VALUE_STT_NEW, EditStatus.IMG_IDX_STT_NEW)
			});
		}

		/// <summary>
		/// 
		/// </summary>
		private void LoadUser()
		{
			try
			{
				UserService usrSv = new UserService();
				_userCollection = usrSv.GetUser();
			}
			catch (Exception ex)
			{
				Util.ShowExceptionBox(ex);
				return;
			}
			_htblGrpContain.Clear();
			_htblFunction.Clear();
			DataTable dtblUsr = _userCollection.DataTableUser;
			dtblUsr.Columns.AddRange(new DataColumn[] {
				new DataColumn(TblCommon.Index,typeof(int)),
				new DataColumn(FIELD_EDIT_STATUS,typeof(string))
			});
			int count = 0;
			foreach (DataRow dtRow in dtblUsr.Rows)
			{
				count++;
				dtRow[TblCommon.Index] = count;
				dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_NONE;
			}
			//
			gridUser.DataSource = dtblUsr;
		}

		private void btnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void btnReload_Click(object sender, EventArgs e)
		{
			this.LoadUser();
		}

		private void gviewUser_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
		{
			int rowHdl = e.FocusedRowHandle;
			gridGrpContain.DataSource = null;
			if (rowHdl < 0)
			{
				this.SetGridDbEditableStatus(true, "");
				return;
			}
			if (_userCollection == null)
				return;
			string userCode = Convert.ToString(gviewUser.GetRowCellValue(rowHdl, TblUser.User_Code));
			object obj = _htblGrpContain[userCode];
			DataTable dtblGrpContain = null;
			if (obj != null)
			{
				dtblGrpContain = (DataTable)obj;
			}
			else
			{
				User user = _userCollection.FindUser(userCode);
				if (user == null)
					return;
				dtblGrpContain = user.ListGroupContain.DataTableGroup;
				dtblGrpContain.Columns.AddRange(new DataColumn[] {
					new DataColumn(TblCommon.Index,typeof(int)),
				});
				int count = 0;
				foreach (DataRow dtRow in dtblGrpContain.Rows)
				{
					count++;
					dtRow[TblCommon.Index] = count;
				}
				//
				_htblGrpContain.Add(userCode, dtblGrpContain);
			}
			gridGrpContain.DataSource = dtblGrpContain;
			//////////////////////////////////////////////////////////////////////////
			object objFbl = _htblFunction[userCode];
			DataTable dtbFunctionBl = null;
			if (objFbl != null)
			{
				dtbFunctionBl = (DataTable)objFbl;
			}
			else
			{
				User user = _userCollection.FindUser(userCode);
				if (user == null)
					return;
				dtbFunctionBl = user.ListFunction.DataTableFunction;
				dtbFunctionBl.Columns.AddRange(new DataColumn[] {
					new DataColumn(TblCommon.Index,typeof(int)),
				});
				int count = 0;
				foreach (DataRow dtRow in dtbFunctionBl.Rows)
				{
					count++;
					dtRow[TblCommon.Index] = count;
				}
				//
				_htblFunction.Add(userCode, dtbFunctionBl);
			}
			gridObjBelong.DataSource = dtbFunctionBl;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="bAllowEdit"></param>
		private void SetGridDbEditableStatus(bool bAllowEdit, string editStatus)
		{
			gviewUser.Columns[TblUser.User_Name].OptionsColumn.AllowEdit = bAllowEdit;
			gviewUser.Columns[TblUser.User_Password].OptionsColumn.AllowEdit = bAllowEdit;
			gviewUser.Columns[TblUser.Flag_Active].OptionsColumn.AllowEdit = bAllowEdit;
			if (editStatus.Equals("") || editStatus.Equals(EditStatus.ITEM_VALUE_STT_NEW))
				gviewUser.Columns[TblUser.User_Code].OptionsColumn.AllowEdit = bAllowEdit;
		}

		private void btnEdit_Click(object sender, EventArgs e)
		{
			int rowHandle = gviewUser.FocusedRowHandle;
			if (rowHandle >= 0)
			{
				string editStatus = Convert.ToString(gviewUser.GetRowCellValue(rowHandle, FIELD_EDIT_STATUS));
				this.SetGridDbEditableStatus(true, editStatus);
				gviewUser.Focus();
				gviewUser.ShowEditor();
			}
		}

		private void gviewUser_BeforeLeaveRow(object sender, DevExpress.XtraGrid.Views.Base.RowAllowEventArgs e)
		{
			this.SetGridDbEditableStatus(false, "");
		}

		private void gviewUser_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
		{
			int rowHandle = e.RowHandle;
			if (rowHandle < 0)
				return;
			DataRow dataRow = gviewUser.GetDataRow(e.RowHandle);
			string editStatus = Convert.ToString(dataRow[FIELD_EDIT_STATUS]);
			if (editStatus.Equals(EditStatus.ITEM_VALUE_STT_NEW))
				return;
			string editCol = e.Column.FieldName;
			if (!(editCol.Equals(TblCommon.Index) || editCol.Equals(FIELD_EDIT_STATUS)))
				dataRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_EDIT;
		}

		private void gviewUser_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e)
		{
			string strFieldName = gviewUser.FocusedColumn.FieldName;
			string strValue = Convert.ToString(e.Value).Trim();
			switch (strFieldName)
			{
				case TblUser.User_Code:
				case TblUser.User_Name:
				case TblUser.Dealer_Code:
				case TblUser.User_Password:
					if (Util.IsStringEmpty(strValue))
					{
						e.ErrorText = MSG_WARNING_EMPTY_VALUE;
						e.Valid = false;
					}
					break;
			}
			//
			if (strFieldName.Equals(TblUser.User_Code))
			{
				DataTable dtblUser = (DataTable)gridUser.DataSource;
				int num = dtblUser.Select(String.Format("{0}='{1}'", TblUser.User_Code, strValue.Trim())).Length;
				if (num > 0)
				{
					e.ErrorText = MSG_WARNING_DUPLICATE_GRP_CODE;
					e.Valid = false;
				}
			}
			//
			if (strFieldName.Equals(TblUser.User_Password))
			{
				if (strValue.Length < 5)
				{
					e.ErrorText = MSG_WARNING_TOO_SHORT_PWD;
					e.Valid = false;
				}
			}
		}

		private void gviewUser_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
		{
			DataRow dtRow = gviewUser.GetDataRow(e.RowHandle);
			dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_NEW;
			dtRow[TblUser.Flag_Active] = Flag.Yes;
			dtRow[TblUser.Flag_Sys_Admin] = Flag.No;
			dtRow[TblCommon.Index] = gviewUser.RowCount + 1; ;
		}

		private void gviewUser_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
		{
			DataRow dtRow = gviewUser.GetDataRow(e.RowHandle);
			string userCode = Convert.ToString(dtRow[TblUser.User_Code]);
			string userName = Convert.ToString(dtRow[TblUser.User_Name]);
			string dealerCode = Convert.ToString(dtRow[TblUser.Dealer_Code]);
			if (Util.IsStringEmpty(userCode))
			{
				gviewUser.SetColumnError(gridColUserCode, ErrorMessage.MSG_WARNING_EMPTY_VALUE);
				e.Valid = false;
			}
			else if (Util.IsStringEmpty(userName))
			{
				gviewUser.SetColumnError(gridColUserName, ErrorMessage.MSG_WARNING_EMPTY_VALUE);
				e.Valid = false;
			}
		}

		private void gviewUser_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
		{
			e.ExceptionMode = ExceptionMode.NoAction;
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			List<String> lstDelUserCode = new List<String>();
			foreach (int rowHandle in gviewUser.GetSelectedRows())
			{
				DataRow dtRow = gviewUser.GetDataRow(rowHandle);
				string editStatus = Convert.ToString(dtRow[FIELD_EDIT_STATUS]);
				if (editStatus.Equals(EditStatus.ITEM_VALUE_STT_NEW))
					lstDelUserCode.Add(Convert.ToString(gviewUser.GetRowCellValue(rowHandle, TblUser.User_Code)));
				else
					dtRow[FIELD_EDIT_STATUS] = EditStatus.ITEM_VALUE_STT_DELETE;
			}
			//
			foreach (string userCode in lstDelUserCode)
			{
				for (int i = 0; i < gviewUser.RowCount; i++)
				{
					string curUserCode = Convert.ToString(gviewUser.GetRowCellValue(i, TblUser.User_Code));
					if (userCode.Equals(curUserCode))
					{
						gviewUser.DeleteRow(i);
						break;
					}
				}
			}
		}

		private void btnApply_Click(object sender, EventArgs e)
		{
			DataSet dsUser = new DataSet();
			DataTable dtblUser = (DataTable)gridUser.DataSource;
			//???????
			//dtblUser.Columns.Add(new DataColumn(TblDealer.Dealer_Code));
			try
			{
				foreach (DataRow dtRow in dtblUser.Rows)
				{
					dtRow[TblDealer.Dealer_Code] = SystemGlobal.strDealerCode;
				}
			}catch (Exception){}
			//
			dtblUser.AcceptChanges();
			//
			foreach (DataRow dtRow in dtblUser.Rows)
			{
				string editStatus = Convert.ToString(dtRow[FIELD_EDIT_STATUS]);
				switch (editStatus)
				{
					case EditStatus.ITEM_VALUE_STT_EDIT:
						dtRow.SetModified();
						break;
					case EditStatus.ITEM_VALUE_STT_NEW:
						dtRow.SetAdded();
						break;
					case EditStatus.ITEM_VALUE_STT_DELETE:
						dtRow.Delete();
						break;
				}
			}
			dtblUser.TableName = DbTable.Tbl_User;
			dsUser.Tables.Add(dtblUser.Copy());
			try
			{
				UserService userSv = new UserService();
				userSv.SaveUser(dsUser);
			}
			catch (Exception ex)
			{
				Util.ShowExceptionBox(ex);
			}
			this.LoadUser();
		}
	}
}
